package org.example.utils;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

import java.util.Base64;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.util.HashMap;
import java.util.Map;

public class QRCodeUtil {
    public static String generateQRCodeBase64(String content) {
        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        Map<EncodeHintType, Object> hints = new HashMap<>();
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H); // 容错等级（H：高）
        hints.put(EncodeHintType.MARGIN, 1); // 边距

        try {
            BitMatrix bitMatrix = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, 200, 200, hints);
//            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
//            BufferedImage image = new BufferedImage(bitMatrix.getWidth(), bitMatrix.getHeight(), BufferedImage.TYPE_INT_RGB);
//            for (int x = 0; x < bitMatrix.getWidth(); x++) {
//                for (int y = 0; y < bitMatrix.getHeight(); y++) {
//                    image.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);
//                }
//            }
//            ImageIO.write(image, "PNG", outputStream);
//            return "data:image/png;base64," + javax.xml.bind.DatatypeConverter.printBase64Binary(outputStream.toByteArray());
////            return javax.xml.bind.DatatypeConverter.printBase64Binary(outputStream.toByteArray());

            ByteArrayOutputStream pngOutputStream = new ByteArrayOutputStream();
            MatrixToImageWriter.writeToStream(bitMatrix, "PNG", pngOutputStream);
            return Base64.getEncoder().encodeToString(pngOutputStream.toByteArray());
        } catch (WriterException | java.io.IOException e) {
            e.printStackTrace();
            return "";
        }
    }
}
